﻿using AsyncTcp.Client;
using FighttheLandOwner.GameCore;
using FighttheLandOwner.Net;
using FighttheLandOwner.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FighttheLandOwner
{
    public partial class Frm_Game : Form
    {
        string name;
        //Game game;
        CardGroup cards;
        List<Card> cardscpy;
        string[] players = new string[3];

        public Frm_Game()
        {
            InitializeComponent();
            cards = new CardGroup(new List<Card>());
            cardscpy = new List<Card>();
            CheckForIllegalCrossThreadCalls = false;
            
        }

        public Frm_Game(string name)
        {
            InitializeComponent();
            //General.Client.ServerDisconnected += Client_ServerDisconnected;
            //General.Client.ServerExceptionOccurred += Client_ServerExceptionOccurred;

            btn_test.Visible = false;
#if DEBUG
            btn_test.Visible = true;
#endif 

            this.name = name;
            lab_this.Text = name;
            cards = new CardGroup(new List<Card>());
            cardscpy = new List<Card>();
            Game.LastGrp = new CardGroup();
            General.Client.PlaintextReceived += Server_PlaintextReceived;
            CheckForIllegalCrossThreadCalls = false;
            btn_cancel.Enabled = false;
            btn_putcard.Enabled = false;
            btn_start.Enabled = false;
        }

        private void Client_ServerExceptionOccurred(object sender, TcpServerExceptionOccurredEventArgs e)
        {
            Environment.Exit(0);
        }

        private void Client_ServerDisconnected(object sender, TcpServerDisconnectedEventArgs e)
        {
            Environment.Exit(0);
        }

        Player Me = new Player();
        
        private void StartGame()
        {
            var g1 = pcb_this.CreateGraphics();
            CardPainter.ShowCards(Me.Cards, new Point(0, 0), g1);
            CardPainter.ShowCardBack(17, new Point(0, 0), pcb_up.CreateGraphics());
            CardPainter.ShowCardBack(17, new Point(0, 0), pcb_down.CreateGraphics());
            if(!Me.IsLandOwner)
            {
                btn_putcard.Enabled = false;
                btn_cancel.Enabled = false;
                btn_start.Enabled = false;
                btn_ready.Enabled = false;
            }
        }

        private void Server_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<string> e)
        {
            var msg = e.Datagram.Split('|');
            //获取上家下家的名字
            if (msg[0] == "players")
            {
                int index = 0;
                for (int i = 1; i < 4; i++)
                {
                    if (msg[i] == name)
                    {
                        index = i;
                        break;
                    }
                }
                switch (index)
                {
                    case 1:
                        lab_down.Text = msg[2];
                        lab_up.Text = msg[3];
                        break;
                    case 2:
                        lab_down.Text = msg[3];
                        lab_up.Text = msg[1];
                        break;
                    case 3:
                        lab_down.Text = msg[1];
                        lab_up.Text = msg[2];
                        break;
                }
            }
            //获取自己的牌
            else if (msg[0] == name)
            {
                string stringcards = msg[1];
                Me.Cards = CardConvert.ToCards(msg[1]);
                Me.Cards = CardManager.Arange(Me.Cards);
                if (Me.Cards.Count == 17) Me.IsLandOwner = false;
                else Me.IsLandOwner = true;
                if (Me.IsLandOwner)
                    btn_putcard.Enabled = true;
                btn_start.Enabled = false;
                btn_ready.Enabled = false;
                StartGame();
            }
            //获取当前出牌玩家
            else if (msg[0] == "whoputcard")
            {
                if (msg[1] == name)
                {
                    btn_putcard.Enabled = true;
                    btn_cancel.Enabled = true;
                }
                else
                {
                    btn_putcard.Enabled = false;
                    btn_cancel.Enabled = false;
                }
            }
            //获取其他玩家出的牌并显示在桌子上
            else if (msg[0] == "deskcard")
            {
                Game.LastGrp = new CardGroup(CardConvert.ToCards(msg[1]));
                var gd = pcb_desk.CreateGraphics();
                gd.Clear(Color.White);
                CardPainter.ShowCards(Game.LastGrp.Cards, new Point(0, 0), gd);
                if (msg[2] != name)
                {
                    Game.Myturn = false;
                    if (msg[2] == lab_down.Text)
                    {
                        var g = pcb_down.CreateGraphics();
                        g.Clear(Color.White);
                        CardPainter.ShowCardBack(int.Parse(msg[3]), new Point(0, 0), g);
                    }
                    else if (msg[2] == lab_up.Text)
                    {
                        var g = pcb_up.CreateGraphics();
                        g.Clear(Color.White);
                        CardPainter.ShowCardBack(int.Parse(msg[3]), new Point(0, 0), g);
                    }
                }
            }
            //轮到谁出牌
            else if (msg[0] == "youplay")
            {
                if (msg[1] == name)
                {
                    btn_putcard.Enabled = true;
                    if (!Game.Myturn)
                        btn_cancel.Enabled = true;
                }
            }
            //某一方胜利
            else if (msg[0] == "win")
            {
                lab_status.Text = msg[1];
                btn_cancel.Enabled = false;
                btn_putcard.Enabled = false;
                btn_ready.Enabled = true;
                btn_ready.Text = "准备";
            }
            //可以开始了
            else if (msg[0] == "canstart")
            {
                if (msg[1] == name)
                {
                    btn_start.Enabled = true;
                }
            }
            //获取地主名称
            else if (msg[0] == "lord")
            {
                lab_lord.Text += msg[1];
            }
            else if (msg[0] == "gameabort")
            {
                MessageBox.Show("有人离开房间，游戏强行关闭");
                Environment.Exit(0);
            }
            else if(msg[0]=="leftcards")
            {
                var leftcards = CardConvert.ToCards(msg[1]);
                var g = pcb_leftcard.CreateGraphics();
                g.Clear(Color.AliceBlue);
                CardPainter.ShowCards(leftcards, new Point(0, 0), g, 140);
            }
        }

        private void btn_putcard_Click(object sender, EventArgs e)
        {
            if (Game.JugeCards(cards.Cards) && Game.JugeOut(cards.Cards))
            {
                General.Client.Send("putcard|" + CardConvert.ToString(cards.Cards)+"|"+(Me.Cards.Count-cards.Cards.Count).ToString());
                btn_putcard.Enabled = false;
                btn_cancel.Enabled = false;
                var g = pcb_this.CreateGraphics();
                g.Clear(Color.White);
                foreach (var c in cards.Cards)
                {
                    Me.Cards.Remove(c);
                }
                CardPainter.ShowCards(Me.Cards, new Point(0, 0), g);
                var gd = pcb_desk.CreateGraphics();
                gd.Clear(Color.White);
                CardPainter.ShowCards(cards.Cards, new Point(0, 0), gd);
                Game.Myturn = true;
                if (Me.Cards.Count == 0)
                {
                    string result=Me.IsLandOwner?"地主胜利":"农民胜利";
                    lab_lord.Text = "地主：";
                    General.Client.Send("win|" + result);
                }
                    
            }

            cards = new CardGroup();
            cardscpy = new List<Card>();
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            General.Client.Send("Start");
            btn_start.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void pcb_up_Click(object sender, EventArgs e)
        {

        }

        private void pcb_this_MouseDown(object sender, MouseEventArgs e)
        {
            //点击牌后，牌的反应

            if (cardscpy.Count == 0)
            {
                cardscpy.Clear();
                cardscpy.AddRange(Me.Cards);
            }
            int offset = 25;
            int loc = e.X / offset;
            if (loc >= Me.Cards.Count && loc <= Me.Cards.Count + 4) loc = Me.Cards.Count - 1;
            else if (loc > Me.Cards.Count + 4) return;
            var g = pcb_this.CreateGraphics();
            if (cardscpy.Contains(Me.Cards[loc]))
            {
                cards.Cards.Add(Me.Cards[loc]);
                cardscpy.Remove(Me.Cards[loc]);
                using (var pen = new Pen(Brushes.Red, 2f))
                {
                    g.DrawLine(pen, offset * loc + 120, 0, offset * loc, 0);
                    g.DrawLine(pen, offset * loc, 0, offset * loc, 180);
                    g.DrawLine(pen, offset * loc + 120, 180, offset * loc, 180);
                }
            }
            else
            {
                cards.Cards.Remove(Me.Cards[loc]);
                using (var pen = new Pen(Brushes.White, 2f))
                {
                    g.DrawLine(pen, offset * loc + 120, 0, offset * loc, 0);
                    g.DrawLine(pen, offset * loc, 0, offset * loc, 180);
                    g.DrawLine(pen, offset * loc + 120, 180, offset * loc, 180);
                }
                cardscpy.Add(Me.Cards[loc]);
            }
        }

        private void pcb_this_Click(object sender, EventArgs e)
        {

        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            General.Client.Send("putcard|null");
            btn_putcard.Enabled = false;
            btn_cancel.Enabled = false;
        }

        private void Frm_Game_FormClosed(object sender, FormClosedEventArgs e)
        {
            General.Client.Send("exit|");
            Environment.Exit(0);
        }


        bool readyflag = false;
        private void btn_ready_Click(object sender, EventArgs e)
        {
            if(!readyflag)
            {
                btn_ready.Text = "取消准备";
                General.Client.Send("ready|" + name);
            }
            else
            {
                btn_ready.Text = "准备";
                General.Client.Send("unready|" + name);
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            Process.Start("FucktheLandOwner.exe");
        }
    }
}
